package com.pzh.usercenter.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzh.usercenter.common.ErrorCode;
import com.pzh.usercenter.contant.UserConstant;
import com.pzh.usercenter.exception.BusinessException;
import com.pzh.usercenter.model.domain.User;
import com.pzh.usercenter.service.UserService;
import com.pzh.usercenter.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author fc3379757631
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-11-15 22:36:53
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    //盐值
    private static final String SALT = "pzh";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
    //1、校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度过短");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        if (planetCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号过长");
        }
        //账户不包含特殊字符
        //正则表达式：
        //\\pP：代表所有的标点符号（Punctuation）。在Unicode标准中，标点符号是一类特定的字符，包括句号、逗号、问号等。
        //\\pS：代表所有的符号（Symbol）。这包括了数学符号、货币符号、箭头等不属于标点符号的特殊字符。
        //\\s+：代表一个或多个空白字符，包括空格、制表符、换行符等。+表示前面的字符（在这个情况下是任何空白字符）可以出现一次或多次。
        String validPattern = "\\pP|\\pS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含特殊字符");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不同");
        }
        //账号不能重复
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //查询账户是否相等
        userQueryWrapper.eq("account", userAccount);
        long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0){
            //账户已存在
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在");
        }

        //星球编号不能重复
         userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(userQueryWrapper);
        if (count > 0){
            //编号已存在
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号已存在");
        }

    //2、加密
        //加盐
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        User user = new User();
        user.setAccount(userAccount);
        user.setPassword(newPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult){
            //保存失败,结果为null
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户保存失败");
        }

        return user.getId();
    }

    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //验证
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度过短");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        //账户不包含特殊字符
        //正则表达式：
        //\\pP：代表所有的标点符号（Punctuation）。在Unicode标准中，标点符号是一类特定的字符，包括句号、逗号、问号等。
        //\\pS：代表所有的符号（Symbol）。这包括了数学符号、货币符号、箭头等不属于标点符号的特殊字符。
        //\\s+：代表一个或多个空白字符，包括空格、制表符、换行符等。+表示前面的字符（在这个情况下是任何空白字符）可以出现一次或多次。
        String validPattern = "\\pP|\\pS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含特殊字符");
        }

        //2、加密
        //加盐
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //查询账户
        // Q:用户被删除还可以被查到吗?
        // S:mybatis plus 提供便捷的逻辑删除支持，自动处理逻辑删除字段
        userQueryWrapper.eq("account", userAccount);
        userQueryWrapper.eq("password", newPassword);

        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null){
            //账号或密码错误
            log.info("The user login fails, and the account and password do not match");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码错误");
        }

        //3、用户脱敏
        //如果使用多了可以封装到DTO
        User safetyUser = getSafetyUser(user);


        //4、设置用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    public User getSafetyUser(User originUser){
        if (originUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setAccount(originUser.getAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setStatus(originUser.getStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    public int userLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }
}




